using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using NGCDS.Properties;

namespace NGCDS
{
    public class LogManager
    {
        private string logFile = Settings.Default.DEFAULT_LOGGING_FILE_NAME;

        public LogManager(string logFileName)
        {
            this.logFile = logFileName;
        }

        public LogHandeler createLogHandler(Session s)
        {
            return new LogHandeler(s);
        }

        public void Flush(LogHandeler logHandler)
        {
            logHandler.Close();

            StreamReader reader = new StreamReader(logHandler.getFilename(), Encoding.Default);
            StreamWriter writer = new StreamWriter(logFile, true, Encoding.Default);

            try
            {
                writer.Write(reader.ReadToEnd());
                writer.Flush();
            }
            catch (IOException ex)
            {
                writer.WriteLine(ex.StackTrace);
                writer.WriteLine(ex.Source);
                writer.WriteLine(ex.Message);
            }
            finally
            {
                reader.Close();
                writer.Close();
                reader = null;
                writer = null;
            }

            if (logHandler.ErrorCount > 0 || logHandler.FatalCount > 0) {
                MailUtil.send(
                    logHandler.getSession().getErrMail(),
                    "NGCDS Error and Fatal Message", 
                    File.ReadAllText(logHandler.getFilename()));
            }

            // clean file
            if (File.Exists(logHandler.getFilename()))
            {
                File.Delete(logHandler.getFilename());
            }
        }
    }
}
